package com.cjm.one.system.service.impl;


import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import com.cjm.one.system.service.CaptchaSystemService;
import com.cjm.one.common.constant.RedisConstants;
import com.cjm.one.model.auth.system.vo.CaptchaCodeVo;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service("captchaSystemServiceImpl")
public class CaptchaSystemServiceImpl implements CaptchaSystemService {
    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public CaptchaCodeVo getCaptchaCode() {
        PasswordEncoder customPasswordEncoder = new BCryptPasswordEncoder();
        String encodePassword = customPasswordEncoder.encode("Cjm123456");
        System.out.println("encodePassword = " + encodePassword);
        CircleCaptcha circleCaptcha = CaptchaUtil.createCircleCaptcha(80, 40, 4, 3);
        String imageBase64 ="data:image/png;base64,"+ circleCaptcha.getImageBase64();
        String code = circleCaptcha.getCode();
        UUID uuid = UUID.randomUUID();
        String codeKey = uuid.toString().replaceAll("-", "");
        redisTemplate.opsForValue().set(RedisConstants.CAPTCHA_IMG_KEY + codeKey, code,RedisConstants.CAPTCHA_IMG_EXPIRE, TimeUnit.SECONDS);
        CaptchaCodeVo captchaCodeVo = new CaptchaCodeVo();
        captchaCodeVo.setCodeKey(codeKey);
        captchaCodeVo.setCode(code);
        captchaCodeVo.setCodeUrl(imageBase64);
        return captchaCodeVo;
    }
}
